/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package libudp;

/**
 *
 * @author davidmessing
 */
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * The Serializer class is a helper class which serializes objects to bytes,
 * and deserializes bytes to objects. Classes must implement Serializable.
 * Serializing converts objects with byte arrays and deserializing converst
 * byte arrays to Objects.
 * @author davidmessing
 */
public class Serializer {
    /**
     * Accepts an Object and returns a byte[].
     * @param obj
     * @return
     * @throws IOException
     */
    public static byte[] serialize(Object obj) throws IOException {
        ByteArrayOutputStream b = new ByteArrayOutputStream();
        ObjectOutputStream o = new ObjectOutputStream(b);
        o.writeObject(obj);
        return b.toByteArray();
    }

    /**
     * Accepts a byte[] and returns an Object.
     * @param bytes
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
        ByteArrayInputStream b = new ByteArrayInputStream(bytes);
        ObjectInputStream o = new ObjectInputStream(b);
        return o.readObject();
    }
}
